<?php
App::import('Sanitize');
class DealsController extends AppController {
	var $name = 'Deals';
	var $uses = array('Deal', 'Product');
	var $helpers = array('Html', 'Session','Thumb');
	var $components = array('Auth','Seo');
	var $paginate = array(
		'limit' => 10,
		'order' => array('Deal.created' => 'desc')
	);

	function searchOption($option) {
		$this->autoRender = false;
		switch ($option) {
			case 'price':
				$this->Session->write('Deal.sort', 'price');
				break;
			case 'created':
				$this->Session->write('Deal.sort', 'created');
				break;
		}
	}

	function beforeFilter() {
		parent::beforeFilter();
	}
	function beforeRender() {
		@$this->set('meta_title', 'Categories');
		@$this->set('meta_description', 'Categories');
		@$this->set('meta_keywords', 'Categories');
	}

	function add($current_product = 1) {
		$user=$this->Auth->user();
		if(!$user){
			$this->redirect(array('controller'=>'users','action'=>'login'));
		}
		$products = $this->Product->find('list', array(
			 'fields' => array('id', 'name')
			 ));
		$this->set(compact('products', 'current_product'));
		if (!empty($this->data)) {
			$this->Deal->create();
			$this->data['Deal']['user_id']=$user['User']['id'];
			if ($this->Deal->save($this->data)) {
				$rId = $this->Deal->getLastInsertID();
				$url='/deals/view/'.$rId;
				$this->Session->setFlash(__('The deal has been saved', true));
				$this->redirect($url);
			}
			else {
				$this->Session->setFlash(__('The deal could not be saved. Please, try again.', true));
			}
		}
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash('__The deal does not exist', true);
			$this->redirect('/products');
		}
		$deal = $this->Deal->findById($id);
		$this->set(compact('deal'));

		$user=$this->Auth->user();
		if($user&&($user['User']['role']==ADMIN || $user['User']['id'] == $deal['Deal']['user_id'])) {
			$this->set('showedit',true);
		}
		else{
			$this->set('showedit',false);
		}
	}

	function index($product_id = null) {
		$this->paginate['conditions'][] = 'Deal.status=0';
		if (!is_null($product_id)) {
			$this->paginate['conditions'][] ='Deal.product_id=' . $product_id;
		}
		if ($this->Session->check('Deal.sort')) {
			$this->paginate['order'] = 'Deal.'.$this->Session->read('Deal.sort') .' ASC';
		}
		$deals = $this->paginate();

		$cart = $this->Session->read('Cart');
		if ('' == $cart) $cart = array();
		foreach($deals as $key => $deal) {
			$deals[$key]['InCart'] = in_array($deal['Deal']['id'], $cart);
		}

		$this->set(compact('deals'));
	}
}
?>
